import { CopyParamAndReturn, FN } from "@Tea/model"

/**
 * @vuese 类型相同的数组或者对象，进行赋值操作
 */
export const changeDataMutual = <T extends {} |[]> (origin: T, data: T) => {
  const keys = Object.keys(origin)
  for (const key of keys) { 
    origin[key] = data[key]
  }
}
/**
 * @vuese 高阶函数 防抖
 * @param fn 
 * @param limit 
 * @returns 
 */
export function debounce<T extends FN>(fn: T, limit: number = 300): CopyParamAndReturn<T> {
  let timer: number, lastResult: any
  return (...args: any[]) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
     lastResult = fn(...args)
    }, limit)
    
    return lastResult
  }
}

/**
 * @vuese 高阶函数 节流
 * @param fn 
 * @param limit 
 * @returns 
 */
export function throttle<T extends FN>(fn: T, limit: number = 300) : CopyParamAndReturn<T>{
  let lastResult: any
  let inThrottle: boolean = false
  return (...args: any[]) => {
    if (!inThrottle) {
      inThrottle = true
      setTimeout(() => {
        inThrottle = false
        lastResult = fn(...args)
      }, limit)
    }
    
    return lastResult
  }
}

/**
 * @use 删除末尾 n 个字符串
 * @param str 
 * @param num 
 * @returns 
 */
export const delLastStr = (str: string, num = 1) => str.substr(0, str.length - num)

/**
 * @use 加入微任务队列
 * @param callback 
 * @returns 
 */
export const joinMicrotask = (callback: FN) => Promise.resolve().then(() => callback())

/**
 * @use 加入宏任务队列
 * @param callback 
 * @returns 
 */
export const joinMacrotask = (callback: FN) => {
  let timer = setTimeout(() => {
    callback()
    timer = null
  })
}

/**
 * @use 获取链表的值
 */

export const getLinkedListValue = function <T extends object, K extends keyof T = keyof T>(obj: T[], valueCode: K, childrenCode: keyof T): T[K][] {
 
  const queue = []

  const _fun = (arr: T[]) => {
     console.log(arr);
     
    arr.forEach(o => {
      queue.push(o[valueCode])
      if (o[childrenCode] instanceof Array) {
        _fun(o[childrenCode] as T[])
      }
    })
  }

  _fun(obj)

  return queue
}